<?php
/**
 * Controller is the customized base controller class.
 * All controller classes for this application should extend from this base class.
 */
class Controller extends CController {
    public $cssFile = null;
    
    public $flag_showRegionsPopup = true;
    
	/**
	 * @var string the default layout for the controller view. Defaults to '//layouts/column1',
	 * meaning using a single column layout. See 'protected/views/layouts/column1.php'.
	 */
	public $layout='//layouts/base';
    
	/**
	 * @var array context menu items. This property will be assigned to {@link CMenu::items}.
	 */
	public $menu=array();
    
	/**
	 * @var array the breadcrumbs of the current page. The value of this property will
	 * be assigned to {@link CBreadcrumbs::links}. Please refer to {@link CBreadcrumbs::links}
	 * for more details on how to specify this property.
	 */
	public $breadcrumbs=array();
    
    public function getBaseUrl() {
        return Yii::app()->getBaseUrl(true);
    }
    
    protected function beforeRender($view) {
        if (!is_null($this->cssFile)) {
            Yii::app()->getClientScript()->registerCssFile($this->cssFile);
        }
        return parent::beforeRender($view);
    }
    
	protected function beforeAction($action) {
		//Debug::dump(array($_SERVER, $this->id , $this->action->id));
		if (!Yii::app()->session['region_id'] && $this->checkCookie('region_id')) {
			Yii::app()->session['region_id'] = intval($this->getCookie('region_id'));
		}

		if (!Yii::app()->session['city_id'] && $this->checkCookie('city_id')) {
			Yii::app()->session['city_id'] = intval($this->getCookie('city_id'));
		}


        if ($this->checkCookie('region_id') && $this->checkCookie('city_id')) {
            $this->flag_showRegionsPopup = false;
        }
		
		$log = array(
			'action' => $this->id.'/'.$this->action->id,
			'ip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '',
			'user_agent' => isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '',
			'referer' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '',
		);
		Controller::logAction($log);		
		
		return parent::beforeAction($action);
	}    
	

	protected function logPageView() {
    /*
		$model = new PageViewLog();
		$model->crdate = time();
		$model->page_key = $this->id.'/'.$this->action->id; 
		$model->ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
		$model->user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
		$model->referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : ''; 
		$model->save();
       */ 
		return true;
	}    
    
    
	/**
	 * general method which can output data and finish script
	 * 
	 * @param unknown_type $data
	 * @param unknown_type $output
	 */
	protected function ajax_responce($data, $output = 'json') {
		if ('json' == $output) {
			$data = json_encode($data);
			$data = (isset($_GET['jsonpcallback'])) ? $_GET['jsonpcallback'].'('.$data.')' : $data;
		}
        header('Content-type: application/json');
		echo $data;
		Yii::app()->end();
	} 	

    /*
    *   Help functions
    */
    public static function checkAdmin() {
    	if (!isset(Yii::app()->user)) return false;
    	if (!isset(Yii::app()->user->usergroup)) return false;
    	return (Yii::app()->user->usergroup == 1);
    }
	
    public function getAdminGroupId() {
    	return 1;
    }	
	
	
    
	public function getLifeTimeInterval($value) {
		if (0 >= intval($value)) return 0;
		return ($value * 86400); // day = 24 * 3600
	}
	
    public static function firmsMediaTypes() {
        return array(
            '1' =>  Yii::t('app', 'Фото'),
            '2' =>  Yii::t('app', 'Видео'),
            '3' =>  Yii::t('app', 'Аудио'),
        );
    }
    
    public static function getFirmsMediaType($key) {
        $data = Controller::firmsMediaTypes();
        return isset($data[$key]) ? $data[$key] : '';
    } 
    
    public static function getServiceTypes() {
        return array(
            '0' =>  Yii::t('app', 'Товары'),
            '1' =>  Yii::t('app', 'Услуги'),
        );        
    }
    
    public static function getServiceType($key) {
        $data = Controller::getServiceTypes();
        return isset($data[$key]) ? $data[$key] : '';
    }     
    
    
    public function actionModelKeyOptions($data = array()) {
        $content = '';
        $pkey = (isset($data['pkey'])) ? $data['pkey'] : CHttpRequest::getParam('pkey');
        if ('' == $pkey) echo 'pkey is not set';
        $key_value = (isset($data['pkey_value'])) ? $data['pkey_value'] : CHttpRequest::getParam($pkey);
        $OptionsModel = (isset($data['model'])) ? $data['model'] : CHttpRequest::getParam('model');
        if ('' == $OptionsModel) echo 'model is undefined';
        $option_value_key = (isset($data['ovkey'])) ? $data['ovkey'] : CHttpRequest::getParam('ovkey');
        $option_label_key = (isset($data['olkey'])) ? $data['olkey'] : CHttpRequest::getParam('olkey');
        
		$this_model = $OptionsModel::model();
        if (0 <= $key_value) {
            $data = $this_model->findAll('hidden = 0 AND '.$pkey.'=:'.$pkey, array(':'.$pkey=> $key_value));	
        } else {
            $data = $this_model->findAll('hidden = 0');
        }
		$content = '';
        $default = intval((isset($data['default'])) ? $data['default'] : CHttpRequest::getParam('default'));
        $default_value_key = (isset($data['dvkey'])) ? $data['dvkey'] : CHttpRequest::getParam('dvkey');
        $default_label_key = (isset($data['dlkey'])) ? $data['dlkey'] : CHttpRequest::getParam('dlkey');
        
		if (0 < $default) {
			$content .= CHtml::tag('option', array('value'=>$default_value_key), $default_label_key,true);
		}
        if (0 >= count($data)) echo $content;
        
	    foreach($data as $row) {
            if (isset($row[$option_value_key]) && isset($row[$option_label_key])) {
                $content .= CHtml::tag('option', array('value'=>$row[$option_value_key]),CHtml::encode($row[$option_label_key]),true);    
            }
	    }
        echo $content;  
        Yii::app()->end();
    }	
	
 
    public function actionGetRubrics() {
        $id = CHttpRequest::getParam('id');
        if (0 > $id) {
            echo Yii::t('app', 'Параметр сервиса не задан.');
            Yii::app()->end();
        }
        $data = array(
            'pkey' => 'service_type',
            'pkey_value' => $id,
            'model' => 'Rubrics',
            'ovkey' => 'id',
            'olkey' => 'name',
            'default' => 0,
//            'dvkey' => '',
//            'dlkey' => '',
        );
        $this->actionModelKeyOptions($data);
    }     
 
 
    public function actionGetCategories() {
        $id = CHttpRequest::getParam('id');
        if (0 >= $id) {
            echo Yii::t('app', 'Параметр рубрики не задан.');
            Yii::app()->end();
        }
        $data = array(
            'pkey' => 'rubric_id',
            'pkey_value' => $id,
            'model' => 'Categories',
            'ovkey' => 'id',
            'olkey' => 'name',
            'default' => 0,
//            'dvkey' => '',
//            'dlkey' => '',
        );
        $this->actionModelKeyOptions($data);
    }    
    
    
    
    public function actionGetCities() {
        $id = CHttpRequest::getParam('id');
        if (0 >= $id) {
            echo Yii::t('app', 'Параметр региона не задан.');
            Yii::app()->end();
        }
        $data = array(
            'pkey' => 'region_id',
            'pkey_value' => $id,
            'model' => 'Cities',
            'ovkey' => 'id',
            'olkey' => 'name',
            'default' => 0,
//            'dvkey' => '',
//            'dlkey' => '',
        );
        $this->actionModelKeyOptions($data);
    }     
    
    
    
    

    public function uploadFirmImg($model, $model_field, $name_prefix = '', $dir_path = '', $instance = 'model') {
        $old_img_name = $model->$model_field;
        $return_data = array(
            'img_name' => $old_img_name,
            'success' => false
        );
        $NewImg = null;
        if ('model' == $instance) {
            $NewImg = CUploadedFile::getInstance($model,$model_field);    
        } else {
            $NewImg = CUploadedFile::getInstanceByName($instance);
        }
        
        if (!$NewImg) return $return_data;
        $model->$model_field = $NewImg;
        if (!$model->validate(array($model_field))) return $return_data;
        $new_img_name = $this->generateImgName($name_prefix).'.'.$NewImg->getExtensionName();
        $img_orig_path_part = ('' != $dir_path) ? $dir_path : $this->getYiiP('firms_img_orig'); //Yii::app()->params['firms_img_orig']; 
        $new_img_orig_path = $this->getRealImgDir($img_orig_path_part.$this->getImgSPathPart($new_img_name));
        if (!$new_img_orig_path) return $return_data;
        if ($NewImg->saveAs($new_img_orig_path.$new_img_name)) {
            $return_data['img_name'] = $new_img_name;
            $return_data['success'] = true;
        }
        return $return_data;
    }

    
    
    public function getYiiP($key) {
        return Yii::app()->params->$key;
    }    
    
    public function resizeFirmImg($imgname, $resize_data) {
        foreach((array)$resize_data as $resize_key => $sizes) {
            $orig_path = $this->getRealImgDir($this->getYiiP('firms_img_orig').$this->getImgSPathPart($imgname));
            $new_path = $this->getRealImgDir($this->getYiiP($resize_key).$this->getImgSPathPart($imgname));
            $this->resizeImg($orig_path.$imgname, $new_path.$imgname, $sizes['w'], $sizes['h']);
        }
        return true;
    }

    public function resizeImg($img, $resize_img, $resizeW,$resizeH, $forse=false) {
        $Image = Yii::app()->image->load($img);
        if (!$Image) return false;
        if ($forse) {
            $Image->resize($resizeW, $resizeH);
        } else {
            if (($Image->height > $resizeH) || ($Image->width > $resizeW) ) {
                $Image->resize($resizeW, $resizeH);
            }
        }
        $Image->save($resize_img);
        return true;
    }    
    

	protected function getFirmImgSrc($name, $key, $mode = 'web') {
		if ('' == $name) return '';
        $img_path = $this->getYiiP($key).$this->getImgSPathPart($name).$name;
		$src = '';
	    switch($mode) {
    		case 'web':
    		default:
    			$src = Yii::app()->getBaseUrl(true).$img_path;
    		break;	
    		case 'real':
    			$src = Yii::getPathOfAlias('webroot').$img_path;
    		break;
    	}
        return $src;
	}     

    public function getRealImgDir($dir) {
		return Controller::getRealDir($dir);
    }
	
	public static function getRealDir($dir) {
        $folder = Yii::getPathOfAlias('webroot').$dir;
        if(is_dir($folder)) return $folder;  
        if (mkdir($folder, 0777, true)) {
            return $folder;
        } else {
            //die('Failed to create folder(s)...');
            return null;
        }		
	}
	
	
    
    public function getImgSPathPart($name) {
        if ('' == $name) return '';
        return $name[0].$name[1].'/'.$name[2].$name[3].'/';
    }
    
    public function generateImgName($prefix='') {
        return md5($prefix.microtime());
    }

    public function regionsData() {
        $all_regions = Yii::app()->basestatic->all_regions;
        $data = array();
        $data[] = array(
            'id' => 0,
            'name' => Yii::t('app', 'Все регионы'),
            'url' => Yii::app()->createUrl('regions/setdata'),
            'has_subregions' => false
        );
        foreach($all_regions as $region) {
            $data_tmp = array(
                'id' => $region['id'],
                'name' => $region['name'],
            );
            if (0 < count($region['cities'])) {
                $data_tmp['url'] = Yii::app()->createUrl('regions/index', array('rid' => $region['id']));
                $data_tmp['has_subregions'] = true;
            } else {
                $data_tmp['url'] = Yii::app()->createUrl('regions/setdata', array('rid' => $region['id']));
                $data_tmp['has_subregions'] = false;
            }
            $data[] = $data_tmp;
        }
        return $data;
    }    
    
    public function getRegionAttr($region_id, $attr) {
        $region = Yii::app()->basestatic->region($region_id);
        $data = '';
        if (isset($region[$attr])) {
            $data = $region[$attr];
        } 
        return $data;
    }
    
    public function getCityAttr($city_id, $attr) {
        $city = Yii::app()->basestatic->city($city_id);
        $data = '';
        if (isset($city[$attr])) {
            $data = $city[$attr];
        } 
        return $data;
    }    
    
    
    /*
    public function getRegionsJson() {
        $all_regions = Yii::app()->basestatic->all_regions;
        $data = array();
        $data [] = array(
            'id' => 0,
            'name' => Yii::t('app', 'Все регионы'),
            'url' => Yii::app()->createUrl('regions/setdata'),
            'has_subregions' => false
        );
        foreach($all_regions as $region) {
            $data_tmp = array(
                'id' => $region['id'],
                'name' => $region['name'],
            );
            if (0 < count($region['cities'])) {
                $data_tmp['url'] = Yii::app()->createUrl('regions/index', array('rid' => $region['id']));
                $data_tmp['has_subregions'] = true;
            } else {
                $data_tmp['url'] = Yii::app()->createUrl('regions/setdata', array('rid' => $region['id']));
                $data_tmp['has_subregions'] = false;
            }
            $data[] = $data_tmp;
        }
        //Debug::dd(json_encode($data));
        return json_encode($data);
    }
*/
    
    
    //work with cookies
	public function unsetCookie($name) {
		$this->setCookie($name,'',time()-60);
        unset(Yii::app()->request->cookies[$name]);
		return true;
	}
	
	public function setCookie($name, $value, $expire = 0, $path = '/', $domain = '') {
		$dom = ('' != $domain) ? $domain : $_SERVER['HTTP_HOST'];
		
        $options = array(
            'domain' => $dom,
            'expire' => $expire,
            'path' => $path,
        );
        Yii::app()->request->cookies[$name] = new CHttpCookie($name, $value, $options);
        return true;
	}
	
	public function getCookie($name) {
		return (isset(Yii::app()->request->cookies[$name])) ? Yii::app()->request->cookies[$name]->value : '';
	}    

    public function checkCookie($name) {
        return (isset(Yii::app()->request->cookies[$name])) ? true : false;
    }
    
    public static function getYandexGeo($model) {
        $data = array(
            'r' => 'error',
            'longitude' => null,
            'latitude' => null,
        );
        $url = 'http://geocode-maps.yandex.ru/1.x/';
        $glue = ' ';
        $country = 'Украина';
        if (1 == Yii::app()->params['default_country_id']) {
          $country = 'Украина';
        } elseif (2 == Yii::app()->params['default_country_id']) {
          $country = 'Россия';
        }
        $geo_reguest = $country.$glue;
        
        $region = Yii::app()->basestatic->region($model->region_id);
        $region = (isset($region['name'])) ? $region['name'].$glue : '';
        
        $city = Yii::app()->basestatic->city($model->city_id);
        $city = (isset($city['name'])) ? $city['name'].$glue : '';
        $geo_reguest .= /*$region.*/$city.$model->address;
        
        $params = array(
            //'key' => '', //@todo: add key
            'format'=>'json',
            'geocode' => $geo_reguest,
        );  
        //Debug::dd($geo_reguest);
        $output = Yii::app()->curl->get($url, $params);
        $output = CJSON::decode($output);
        if (!isset($output['response']['GeoObjectCollection']['featureMember'][0]['GeoObject']['Point']['pos'])) return $data;
        $coords = explode(' ', $output['response']['GeoObjectCollection']['featureMember'][0]['GeoObject']['Point']['pos']);
        
        $data['r'] = 'success';
        $data['longitude'] = $coords[0];
        $data['latitude'] = $coords[1];

        return $data;
    }
    
	
	public static function blowfishSalt($cost = 13) {
		if (!is_numeric($cost) || $cost < 4 || $cost > 31) {
			throw new Exception("cost parameter must be between 4 and 31");
		}
		$rand = array();
		for ($i = 0; $i < 8; $i += 1) {
			$rand[] = pack('S', mt_rand(0, 0xffff));
		}
		$rand[] = substr(microtime(), 2, 6);
		$rand = sha1(implode('', $rand), true);
		$salt = '$2a$' . sprintf('%02d', $cost) . '$';
		$salt .= strtr(substr(base64_encode($rand), 0, 22), array('+' => '.'));
		return $salt;
	}
	
	
	public static function logAction($log) {
		$time = time();
		$data = array();
		$data['logtime_h'] = date('Y-m-d H:i:s', $time);
		$data['logtime'] = $time;
		$data = $data + $log;
		$log_file = Controller::getRealDir(Yii::app()->params->log_path_actions).date('Y_m_d', $time).'.log';
		$src = json_encode($data).PHP_EOL;
		error_log($src, 3, $log_file);
		return true;
	}
	
	
    
}